<?php

namespace App\Models\CacheModel;

use App\Models\Api\BaseCache;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Log;
use AstroTool\Cache\CacheManage;

/**
 * 小程序鸡汤词条数据模型
 * Class MiniDateText
 * @package App\Models\CacheModel
 */
class MiniDateText extends BaseCache
{
    private const LOG_PRE = '小程序MiniDateText Model 异常：';
    protected $table = 'wechat_backup_07_18_14_43_00.mini_date_text';

    protected $cacheModel = 'mini.word';

    /**
     * 获取今日鸡汤词条
     * @param int $time 今日时间
     * @param int $type 1=>今日鸡汤，2=》本周鸡汤
     * @return string
     * @throws Exception
     */
    public function getWord($time = 20191207, $type = 1)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $time . '-' . $type)->getDataAndSet(function () use ($time, $type)
        {
            return $this->getWordFromDB($time, $type);

        });
    }

    /**
     * 获取鸡汤词条
     * @param int $time
     * @param int $type 1=>今日鸡汤，2=》本周鸡汤
     * @return string
     */
    private function getWordFromDB($time = 20191207, $type = 1)
    {
        try
        {
            $data = $this->field('text')->where(['date' => $time, 'type' => $type])->findOrFail();
            $data = json_decode(json_encode($data, true), true);
            if (isset($data['text']))
            {
                $data = $data['text'];
            }
        }
        catch (DataNotFoundException $e)
        {
            $data = ' ';
//            Log::write('获取鸡汤词条失败：time=' . $time . ' type=' . $type, 'error');
        }
        catch (ModelNotFoundException $e)
        {
            $data = '';
        }
        catch (Exception $e)
        {
            $data = ' ';
//            Log::write(self::LOG_PRE . $e->getMessage() . ' ' . $e->getFile() . ':' . $e->getLine(), 'error');
        }
        return $data;
    }
}
